package com.example.androidtest;

import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback{
	public static final  int MAX_SIZE=384;
	SurfaceHolder holder;
	Paint mPaint;
	Paint mClearPaint;
	Canvas canvas;
	Context mContext;
	Path mPath;
	
	/**
	 * earlier data corresponds to large number index
	 */
	List<Integer> dataList;
	
	public MySurfaceView(Context context) {
		super(context);
		mContext=context;
		init();
		
	}
	

	private void init(){
		holder=this.getHolder();
		holder.addCallback(this);
		
		//init the mPaint
		mPaint=new Paint();
		mPaint.setColor(Color.RED);
		mPaint.setStyle(Paint.Style.STROKE); //solid
		mPaint.setStrokeWidth(2);	//set the thickness
		mClearPaint=new Paint();
		mClearPaint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR));
		dataList=new LinkedList<Integer>();
	}
	
	public MySurfaceView(Context context,AttributeSet attrs) {
//		this(context);
		super(context, attrs);
		mContext=context;
		init();
	}
	
	public Paint getPaint(){
		return mPaint;
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		Log.d("MainActivity", "SurfaceView created");

	}
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
	}
	
	/**
	 * Add a y data
	 * @param y
	 */
	synchronized private void addData(Integer y){
		if(dataList.size()<MySurfaceView.MAX_SIZE){
			dataList.add(0,y);
		}else {
			dataList.remove(dataList.size()-1);
			dataList.add(0, y); }
	}
	
	public void onDataReceived(){

		Log.d("MainActivity", "SurfaceView created");
		MyApp app=(MyApp)mContext.getApplicationContext();
		int[] ydatas=app.getYDatas();
		for(int i=0;i<ydatas.length;i++){
			addData(new Integer(ydatas[i]));
		}
		refresh();
		postInvalidate();
	}
	
	/**
	 * call this function to refresh the drawing once
	 */
	synchronized public void refresh(){
		
		Path path=new Path();
		for(int i=0;i<dataList.size();i++){
			Point p=new Point(i,dataList.get(i));
			path.lineTo(3*p.x, p.y);
		}
		Canvas canvas=holder.lockCanvas();
		canvas.drawPaint(mClearPaint);
		canvas.drawPath(path, mPaint);
		holder.unlockCanvasAndPost(canvas);
	}
	
	
	

}
